package day13;

import sun.management.counter.Units;

import java.util.concurrent.*;

//定义自定义线程池
public class MyThreadPool<S> {
    //提供七大核心参数的属性
    //1.定义核心线程数 如果是单线程池 核心数量为1
    private final int core_num = 10;
    //2.定义最大线程数
    private final int max_num = 1000;
    //3.定义存活时间
    private final long alive_time = 30;
    //4.定义时间单位
    private final TimeUnit unit = TimeUnit.SECONDS;
    //5.定义工作队列(任务队列)
    private final BlockingQueue<Runnable> queue = new ArrayBlockingQueue(core_num);
    //6.定义线程工厂
    private final ThreadFactory factory = Executors.defaultThreadFactory();
    //7.定义拒绝策略
    private final RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    //8.定义线程池对象(利用上面的7个参数)
    private final ExecutorService pool;
    //利用ThreadPoolExecutor构造方法 来创建线程池
    public MyThreadPool(){
        pool = new ThreadPoolExecutor(core_num,max_num,alive_time,unit,queue,factory,handler);
    }
    //在线程池中 添加任务的方法 execute
    //返回true执行任务成功 否则false
    public boolean execute(Runnable r){
        try {
            pool.execute(r);
            return true;
        } catch (Exception e) {
            System.out.println("执行任务失败");
            return false;
        }
    }
    //提供一个execute(Callable)方法的重载
    //定义自定义泛型     后面使用泛型
    public Future<S> execute(Callable<S> c){
        Future<S> f = null;
        try {
            f = pool.submit(c);
        } catch (Exception e) {
            System.out.println("执行任务失败");
        }
        return f;
    }
    //定义关闭线程池的方法
    public void shutdown(){
        pool.shutdown();
    }
}
class TestPool{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.创建线程池
        MyThreadPool pool = new MyThreadPool();
        //2.执行任务
        for (int i = 0; i < 100; i++) {
            /*pool.execute(()->{
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });*/
           Future<Long> f =  pool.execute(()->{
               Thread t = Thread.currentThread();
               System.out.println(t.getName());
               return t.getId();
            });
           Long result = f.get();
            System.out.println("Callable结果："+result);
        }
        //3.关闭
        pool.shutdown();
    }
}